﻿using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Threading;

namespace CmsDatabaseMigrations
{
    /// <summary>
    /// Contains migration configuration settings
    /// </summary>
    public static class MigrationsConfiguration
    {
        /// <summary>
        /// Absolute path to folder with stored procedure files
        /// </summary>
        public static string PathToStoredProcedures
        {
            get { return ConfigurationManager.AppSettings["Migration::ProceduresPath"]; }
        }

        /// <summary>
        /// Name of connection string that should be used for appliing migrations
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                var name = ConfigurationManager.AppSettings["Migration::Connection"];
                if (string.IsNullOrEmpty(name))
                {
                    throw new ConfigurationErrorsException(
                        "Please specify connection string name in AppSettings section with key 'Migration::Connection'");
                }

                var connection = ConfigurationManager.ConnectionStrings[name];
                if (connection == null)
                {
                    string additionalName = ConfigurationManager.AppSettings[name];
                    if (!string.IsNullOrEmpty(additionalName))
                    {
                        connection = ConfigurationManager.ConnectionStrings[additionalName];
                    }
                    if (connection == null)
                    {
                        throw new ConfigurationErrorsException(
                            string.Format("Please specify connection string with name '{0}'", name));
                    }
                }

                return connection.ConnectionString;
            }
        }

        /// <summary>
        /// Path to filder which contains assembly with migrations
        /// </summary>
        public static string PathToMigrationsAssembly
        {
            get
            {
                return ConfigurationManager.AppSettings["Migration::AssemblyPath"] ??
                       Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "CmsDatabaseMigrations.dll");
            }
        }
    }
}